package com.my.input;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author marshal
 * @version 2021-05-21
 */
public class FileInputStreamTest {
    public static void main(String[] args) {
//        readByBuff();
        readByBuff2();
    }

    /**
     * 1. 传统模式，通过tar-catch-finally代码块来捕捉异常，并且在finally语句块中关闭资源
     */
    public static void readByBuff() {
        FileInputStream fi = null;
        try {
            fi = new FileInputStream("file/poem.txt");
            var bbuf = new byte[1024];
            // 用于保存实际读取的字节数
            var hasRead = 0;
            while ((hasRead = fi.read(bbuf)) > 0) {
                System.out.println(new String(bbuf, 0, hasRead));
            }
        } catch (IOException e) {
            System.out.println("异常信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            System.out.println("finally 关闭资源");
            try {
                if (fi != null) {
                    fi.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 2. 通过try-with-resource语句来自动关闭资源
     * 参考：https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
     */
    public static void readByBuff2() {
        try (FileInputStream fi = new FileInputStream("file/poem.txt")) {
            // 每个汉语字符都是3个字节，使用18字节的字节数组，刚好可以完整的读完一句诗
            var bbuf = new byte[18];
            var hasRead = 0;
            while ((hasRead = fi.read(bbuf)) > 0) {
                System.out.println(new String(bbuf, 0, hasRead));
            }
        } catch (IOException e) {
            System.out.println("异常信息：" + e.getMessage());
        }
    }

    public static void readByBuff3() throws IOException {
        FileInputStream fi = new FileInputStream("file/poem.txt");
        var bbuf = new byte[1024];
        var hasRead = 0;
        while ((hasRead = fi.read(bbuf)) > 0) {
            System.out.println(new String(bbuf, 0, hasRead));
        }
    }

}
